import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
import { getLocation as getLocationInfo, getOpenId} from '@/api/common'

const store = new Vuex.Store({
	state: {
		location: {},
		openId: undefined,
		tabBars:[],
		addressOptions: uni.getStorageSync('addressOptions') || []
	},
	mutations: {
		SET_TAB_BARS(state,data){
			state.tabBars = data
		},
		SET_LOCATION(state, data) {
			state.location = data
		},
		SET_OPENID(state,openId) {
			state.openId = openId
		},
		SET_ADDRESS(state, data) {
			state.addressOptions = data;
			uni.setStorageSync('addressOptions',data)
		}
	},
	actions: {
		getLocation({commit}) {
			let _this = this
			let longitude = null;
			let latitude = null;
			
			return new Promise((resolve, reject) => {
				getLocation()
				
				// 获取经纬度
				function getLocation() {
					uni.getLocation({
						type: 'gcj02',
						success(res) {
							longitude = res.longitude
							latitude = res.latitude
							getSite()
						},
						fail(err) {
							getAuth()
							console.error('获取位置信息失败', err)
						}
					});
				}
				
				// 获取位置权限
				function getAuth() {
					uni.getSetting({
						success(res) {
							if (!res.authSetting['scope.userLocation']) {
								uni.authorize({
									scope: 'scope.userLocation',
									success() {
										//这里是用户同意授权后的回调
										console.log('同意获取地址')
										getLocation()
									},
									fail() { //这里是用户拒绝授权后的回调
										uni.showToast({
											title: "您拒绝了授权当前位置",
											icon: "none"
										});
										console.log('您拒绝了授权当前位置')
									}
								})
							} else { //用户已经授权过了
								console.log('用户已经授权过了')
							}
						},
						fail(err) {
							reject(err)
							console.log(err)
						}
					})
				}
				
				
				// 获取位置信息
				function getSite() {
					let data = {
						lng: longitude,
						lat: latitude
					}
					getLocationInfo(data).then(res => {
						resolve(res)
						commit('SET_LOCATION', res)
					}).catch(err => {
						reject(err)
					})
				}
			})
		},
		getOpenid({commit}) {
			return new Promise((resolve, reject) => {
				uni.login({
					provider: "weixin",
					success: loginRes => {
						console.log(loginRes)
						getOpenId({code: loginRes.code}).then(res => {
							commit('SET_OPENID',res.openid)
							resolve(res)
						})
					}
				})
			})
			
		},
		getAddress({commit}) {
			uni.request({
				url: 'https://qiyeji.oss-cn-beijing.aliyuncs.com/file/address.json',
				success(res) {
					commit('SET_ADDRESS',res.data)
				}
			})
		}
	}
})

export default store